﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Jermaine.Serialization
{
    public class Cloning
    {
        public static T DeepCopy<T>(T o) {
            if (o == null) {
                throw new NullReferenceException();
            }
            var type = o.GetType();
            if (!type.Attributes.HasFlag(TypeAttributes.Serializable)) {
                throw new Exception("Class must be marked with Serializable");
            }

            T cloned = default(T);

            using (var ms = new MemoryStream()) {
                var bf = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
                bf.Serialize(ms, o);
                ms.Seek(0, SeekOrigin.Begin);
                cloned = (T)bf.Deserialize(ms);
            }
            return cloned;
        }



        public static T ShadowCopy<T>(T o) where T : ICloneable {
            return (T)o.Clone();
        }
    }
}
